package event

import (
	"fmt"
	"mmo/core"
	"zinxtcp/ziface"
)

type ConnEvent struct{}

func (ce *ConnEvent) GetConnBegin() func(ziface.IConnection) {
	return OnConnecionAdd
}

func (ce *ConnEvent) GetConnStop() func(ziface.IConnection) {
	return OnConnectionLost
}

//当客户端建立连接的时候的hook函数
func OnConnecionAdd(conn ziface.IConnection) {
	//创建一个玩家
	player := core.NewPlayer(conn)

	//将当前新上线玩家添加到worldManager中
	core.WorldMgrObj.AddPlayer(player)

	//同步当前的PlayerID给客户端， 走MsgID:1 消息
	player.SyncPid()

	//同步当前玩家的初始化坐标信息给客户端，走MsgID:200消息
	player.BroadCastStartPosition()

	//将该连接绑定属性Pid
	conn.SetProperty("pid", player.Pid)

	//同步周边玩家上线信息，与现实周边玩家信息
	player.SyncSurrounding()

	fmt.Println("=====> Player pidId = ", player.Pid, " arrived ====")
}

//当客户端断开连接的时候的hook函数
func OnConnectionLost(conn ziface.IConnection) {
	//获取当前连接的Pid属性
	pid, _ := conn.GetProperty("pid")
	gid, _ := conn.GetProperty("gid")
	core.WorldMgrObj.RemovePlayerByPid(pid.(int32))
	core.WorldMgrObj.AoiMgr.RemovePidFromGrid(pid.(int32), gid.(int))
	//go core.WorldMgrObj.AoiMgr.RemovePid(pid.(int32))
	//根据pid获取对应的玩家对象
	player := core.WorldMgrObj.GetPlayerByPid(pid.(int32))
	player.LostConnection1(pid.(int32), gid.(int))
	fmt.Println("====> Player ", pid, " left =====")

}
